﻿using Renci.SshNet;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Publicuse.Util
{
    /// <summary>
    /// SFTP工具类
    /// </summary>
    public class SftpUtil
    {
        #region 字段或属性
        private SftpClient sftp;
        /// <summary>
        /// SFTP连接状态
        /// </summary>
        public bool Connected { get { return sftp.IsConnected; } }
        #endregion

        #region 构造
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        /// <param name="user">用户名</param>
        /// <param name="pwd">密码</param>
        public SftpUtil(string ip, string port, string user, string pwd)
        {
            sftp = new SftpClient(ip, Int32.Parse(port), user, pwd);
        }
        #endregion

        #region 连接SFTP
        /// <summary>
        /// 连接SFTP
        /// </summary>
        /// <returns>true成功</returns>
        public bool Connect()
        {
            try
            {
                if (!Connected)
                {
                    sftp.Connect();
                }
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("连接SFTP失败，原因：{0}", ex.Message));
            }
        }
        #endregion

        #region 断开SFTP
        /// <summary>
        /// 断开SFTP
        /// </summary> 
        public void Disconnect()
        {
            try
            {
                if (sftp != null && Connected)
                {
                    sftp.Disconnect();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("断开SFTP失败，原因：{0}", ex.Message));
            }
        }
        #endregion

        #region SFTP上传文件
        /// <summary>
        /// SFTP上传文件
        /// </summary>
        /// <param name="localPath">本地路径</param>
        /// <param name="remotePath">远程路径</param>
        public void Put(string localPath, string remotePath, string filename, out string msg)
        {
            msg = null;
            try
            {
                using (var file = File.OpenRead(localPath))
                {
                    Connect();
                    if (!sftp.Exists(remotePath))
                    {
                        var files = remotePath.Split('/');
                        var path = string.Empty;
                        for (int i = 0; i < files.Length; i++)
                        {
                            if (i == 0)
                            {
                                path = files[i] + "/";
                            }
                            else
                            {
                                path += files[i] + "/";
                                if (!sftp.Exists(path))
                                    sftp.CreateDirectory(path);
                            }
                        }
                    }
                    sftp.UploadFile(file, remotePath + "/" + filename);
                    Disconnect();
                }
            }
            catch (Exception ex)
            {
                msg = string.Format("SFTP文件上传失败，原因：{0}", ex.Message);
                throw new Exception(msg);
            }
        }
        #endregion

        #region SFTP获取文件
        /// <summary>
        /// SFTP获取文件
        /// </summary>
        /// <param name="remotePath">远程路径</param>
        /// <param name="localPath">本地路径</param>
        public void Get(string remotePath, string localPath)
        {
            try
            {
                Connect();
                var byt = sftp.ReadAllBytes(remotePath);
                Disconnect();
                File.WriteAllBytes(localPath, byt);
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件获取失败，原因：{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件获取失败，原因：{0}", ex.Message));
            }

        }
        #endregion

        #region 删除SFTP文件
        /// <summary>
        /// 删除SFTP文件 
        /// </summary>
        /// <param name="remoteFile">远程路径</param>
        public void Delete(string remoteFile)
        {
            try
            {
                Connect();
                sftp.Delete(remoteFile);
                Disconnect();
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件删除失败，原因：{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件删除失败，原因：{0}", ex.Message));
            }
        }
        #endregion

        /// <summary>
        /// 上传文件初始化
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="today"></param>
        /// <param name="ftpb"></param>
        /// <param name="ftpFilePath"></param>
        public static void UploadInit(out string msg, string today, string ftpb, string ftpPath)
        {
            msg = null;
            //var ftp = ConfigurationManager.AppSettings["ftp"].Split(';');
            var ftp = ftpb.Split(';');
            FtpUtil.ftpServerIP = ftp[0];
            var User = ftp[1].Split(':')[0];
            var Pass = ftp[1].Split(':')[1];
            var Host = FtpUtil.ftpServerIP.Split(':')[1].Replace("/", "");
            var Port = FtpUtil.ftpServerIP.Split(':')[2].Replace("/", "");
            SftpUtil objSFTPHelper = new SftpUtil(Host, Port, User, Pass);
            string localPath = AppDomain.CurrentDomain.BaseDirectory + "如约数据分析/";
            //var ftpPath = ConfigurationManager.AppSettings["ftpFilePath"];

            string dir = localPath + "/" + today;
            //检测本地目录是否存在  
            if (!Directory.Exists(dir))
            {
                msg = "请先选择时间执行生成报表数据";
                return;
            }
            string[] strFiles = Directory.GetFiles(dir);
            if (strFiles != null)
            {
                foreach (string strFile in strFiles)
                {
                    string filename = Path.GetFileName(strFile);
                    var uploadfile = ftpPath + "/" + today;
                    objSFTPHelper.Put(strFile, uploadfile, filename, out msg);
                    if (!string.IsNullOrEmpty(msg))
                    {
                        break;
                    }
                }
            }
        }

        #region 获取SFTP文件列表
        /// <summary>
        /// 获取SFTP文件列表
        /// </summary>
        /// <param name="remotePath">远程目录</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <returns></returns>
        public ArrayList GetFileList(string remotePath, string fileSuffix)
        {
            try
            {
                Connect();
                var files = sftp.ListDirectory(remotePath);
                Disconnect();
                var objList = new ArrayList();
                foreach (var file in files)
                {
                    string name = file.Name;
                    if (name.Length > (fileSuffix.Length + 1) && fileSuffix == name.Substring(name.Length - fileSuffix.Length))
                    {
                        objList.Add(name);
                    }
                }
                return objList;
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
            }
        }
        #endregion

        #region 移动SFTP文件
        /// <summary>
        /// 移动SFTP文件
        /// </summary>
        /// <param name="oldRemotePath">旧远程路径</param>
        /// <param name="newRemotePath">新远程路径</param>
        public void Move(string oldRemotePath, string newRemotePath)
        {
            try
            {
                Connect();
                sftp.RenameFile(oldRemotePath, newRemotePath);
                Disconnect();
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件移动失败，原因：{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件移动失败，原因：{0}", ex.Message));
            }
        }
        #endregion
    }
}
